import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { ResCode } from './common/constants';
import { getLogStr } from './common/utils';
import { Logger } from './utils/log4js';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const logFormat = `Request original url: ${request.originalUrl}
    Method: ${request.method}
    IP: ${request.ip}
    Status code: ${status}
    Response: ${exception.toString()}`;
    Logger.error(getLogStr(logFormat));
    if (exception['response'] && exception['response'].statusCode == 403) {
      response.status(200).json({
        code: ResCode.FORBIDDEN,
        message: '禁止访问',
      });
    } else {
      response.status(200).json({
        code: ResCode.ERROR,
        message: 'system exception',
        exception: exception['response'] || null
      });
    }
  }
}
